package com.main.ok.util;

/*
 * Project: greenline-hrs-open-service-war
 * 
 * File Created at 2012-6-18
 * 
 * Copyright 2012 Greenline.com Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Greenline Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Greenline.com.
 */

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Type XmlConverter
 * @Desc
 * @author weirui.shenwr
 * @date 2012-6-18
 * @Version V1.0
 */
public class XmlConverter {

    private static final Log log = LogFactory.getLog(XmlConverter.class);

    /**
     * 对象转xml
     * 
     * @param t
     * @param classiz
     * @return
     */
    public static <T> String toXML(T t, Class<T> classiz) {
        try {
            JAXBContext context = JAXBContext.newInstance(classiz);
            Marshaller marshaller = context.createMarshaller();
            StringWriter sw = new StringWriter();
            marshaller.marshal(t, sw);
            return sw.toString();
        } catch (Exception e) {
            log.error("toXML error.", e);
            return "";
        }
    }

    /**
     * xml转对象
     * 
     * @param classiz
     * @param xml
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T toObject(Class<T> classiz, String xml) {
        try {
            if (StringUtils.isEmpty(xml)) {
                return null;
            }
            JAXBContext context = JAXBContext.newInstance(classiz);
            Unmarshaller unMarshaller = context.createUnmarshaller();
            return (T) unMarshaller.unmarshal(new StringReader(xml));
        } catch (Exception e) {
            log.error("getObjct error.", e);
            return null;
        }
    }

}
